package com.jcx.ldzj.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.jcx.ldzj.config.UserConfig;
import com.jcx.ldzj.emun.MyCode;
import com.jcx.ldzj.entity.RoleMenuRelation;
import com.jcx.ldzj.dao.RoleMenuRelationMapper;
import com.jcx.ldzj.entity.UserRoleRelation;
import com.jcx.ldzj.service.IRoleMenuRelationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcx.ldzj.service.IUserInfoService;
import com.jcx.ldzj.service.IUserRoleRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限角色关联表 服务实现类
 * </p>
 *
 * @author ld
 * @since 2021-08-10
 */
@Slf4j
@Service
public class RoleMenuRelationServiceImpl extends ServiceImpl<RoleMenuRelationMapper, RoleMenuRelation> implements IRoleMenuRelationService {

    @Autowired
    private IUserRoleRelationService iUserRoleRelationService;
    @Autowired
    private UserConfig userConfig;
    @Autowired
    private IUserInfoService iUserInfoService;

    @Override
    public List<RoleMenuRelation> getRolesBymenuId(String menuId) {

        return this.baseMapper.getRolesBymenuId(menuId);
    }

    @Override
    public List<RoleMenuRelation> getMenuByRoleId(String roleId) {
        return this.baseMapper.getMenuByRoleId(roleId);
    }

    @Override
    @Transactional
    public R updateMenuByRoleId(List<Long> menuId, String roleId) {
        this.baseMapper.deleteMenuByRoleId(roleId);
        this.addMenuByRoleId(menuId,roleId);
        List<UserRoleRelation> list = iUserRoleRelationService.getByroleId(roleId);
        List<String> collect = list.stream().map(UserRoleRelation::getUserId).collect(Collectors.toList());
        Set<String> set=new HashSet(collect);
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String str = it.next();
            userConfig.setRoles(iUserInfoService.getById(str));
        }
        return R.ok("成功");
    }

    @Override
    public R addMenuByRoleId(List<Long> menuIds, String roleId) {
        boolean flag=false;
        for (int i = 0;menuIds!=null&& i < menuIds.size(); i++) {
            try {
                RoleMenuRelation relation=new RoleMenuRelation();
                relation.setRoleId(roleId);
                relation.setMenuId(menuIds.get(i));
                this.save(relation);
            }catch (Exception e){
                log.error(MyCode.新增角色与菜单关系失败.getMsg()+"失败的角色id为：{}失败的菜单id为：{}错误原因：{}",roleId,menuIds.get(i),e.toString());
                flag=true;
            }
        }
        if(flag){
            return R.failed(MyCode.新增角色与菜单关系失败.getMsg());
        }
        return R.ok("成功");
    }
}
